<template>
  <div class="template-selector">
    <el-dialog
      title="选择审批流程模板"
      :visible.sync="dialogVisible"
      width="900px"
      append-to-body
      @close="handleClose">
      <div class="selector-container">
        <!-- 提示信息 -->
        <el-alert
          title="往期审批模板复用"
          type="info"
          description="您可以从历史审批模板中选择一个进行复用，这将继承原模板的所有审批流程设置。"
          :closable="false"
          show-icon
          style="margin-bottom: 15px;"
        >
          <div slot="title" style="font-weight: bold;">
            <i class="el-icon-info" style="margin-right: 5px;"></i>
            往期审批模板复用
          </div>
        </el-alert>

        <!-- 搜索区域 -->
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="模板名称" prop="templateName">
            <el-input
              v-model="queryParams.templateName"
              placeholder="请输入模板名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
              <el-option label="启用" value="0"/>
              <el-option label="停用" value="1"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 操作工具栏 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="createNewTemplate"
              v-hasPermi="['supply:template:add']"
            >新增模板
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格区域 -->
        <el-table v-loading="loading" :data="templateList" @row-click="handleRowClick" row-key="id" highlight-current-row>
          <el-table-column label="序号" align="center" type="index" width="50"/>
          <el-table-column label="模板名称" align="center" prop="templateName" :show-overflow-tooltip="true"/>
          <el-table-column label="模板描述" align="center" prop="templateDesc" :show-overflow-tooltip="true"/>
          <el-table-column label="流程类型" align="center" prop="flowType" :formatter="flowTypeFormat"/>
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="签名记录" align="center" min-width="120">
            <template slot-scope="scope">
              <div v-if="scope.row.signatureImage" class="signature-list">
                <el-image
                  v-for="(img, index) in getSignatureImages(scope.row.signatureImage)"
                  :key="index"
                  :src="img"
                  :preview-src-list="getSignatureImages(scope.row.signatureImage)"
                  class="signature-thumb"
                  fit="contain">
                  <div slot="error" class="image-error">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
              <span v-else>暂无签名</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click.stop="handlePreview(scope.row)"
                v-hasPermi="['supply:flowTemplate:query']"
              >预览
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-check"
                @click.stop="selectTemplate(scope.row)"
              >选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="confirmSelection" :disabled="!selectedTemplate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 预览流程图对话框 -->
    <el-dialog title="预览审批流程" :visible.sync="previewOpen" width="900px" append-to-body>
      <div class="flow-preview-container">
        <div class="flow-preview">
          <div v-if="!previewData || !previewData.nodes || previewData.nodes.length === 0" class="no-data">
            <i class="el-icon-warning-outline"></i>
            <p>暂无流程数据</p>
          </div>

          <template v-else>
            <div class="flow-start">
              <div class="start-node">
                <i class="el-icon-s-platform"></i>
                <span>开始</span>
              </div>
              <div class="flow-connector"></div>
            </div>

            <div
              v-for="(node, index) in previewData.nodes"
              :key="index"
              class="flow-node-wrapper"
            >
              <div class="flow-node">
                <div class="node-icon">
                  <i class="el-icon-s-check"></i>
                </div>
                <div class="node-content">
                  <div class="node-title">{{ node.nodeName }}</div>
                  <div class="node-info">
                    <p v-if="node.approvalRoles && node.approvalRoles.length">
                      审批角色: {{ formatRoles(node.approvalRoles) }}
                    </p>
                    <p v-if="node.approvalUsers && node.approvalUsers.length">
                      审批人员: {{ formatApprovalUsers(node.approvalUsers) }}
                    </p>
                    <p>审批人数: {{ node.approverCount || 1 }}</p>
                    <p v-if="node.needSignature">
                      电子签名: <i class="el-icon-check success-icon"></i> 已启用
                    </p>
                    <!-- 签名图片显示 -->
                    <div v-if="node.signatureImage" class="signature-images">
                      <p>签名记录:</p>
                      <div class="image-list">
                        <el-image
                          v-for="(img, imgIndex) in getSignatureImages(node.signatureImage)"
                          :key="imgIndex"
                          :src="img"
                          :preview-src-list="getSignatureImages(node.signatureImage)"
                          class="signature-thumb"
                          fit="contain">
                          <div slot="error" class="image-error">
                            <i class="el-icon-picture-outline"></i>
                          </div>
                        </el-image>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 连接线 -->
              <div v-if="index < previewData.nodes.length - 1" class="flow-connector">
                <i class="el-icon-arrow-down"></i>
              </div>
            </div>

            <div class="flow-end">
              <div class="flow-connector"></div>
              <div class="end-node">
                <i class="el-icon-s-release"></i>
                <span>结束</span>
              </div>
            </div>
          </template>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate } from "@/api/supply/template";

export default {
  name: "TemplateSelector",
  dicts: ['sys_normal_disable'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    productId: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审批流程模板表格数据
      templateList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: undefined,
        flowType: undefined,
        status: undefined
      },
      // 选中的模板
      selectedTemplate: null,
      // 对话框可见性
      dialogVisible: false,
      // 预览相关
      previewOpen: false,
      previewData: null
    };
  },
  computed: {
    // 计算选中模板的ID
    selectedTemplateId() {
      return this.selectedTemplate ? this.selectedTemplate.id : null;
    }
  },
  watch: {
    visible: {
      handler(val) {
        this.dialogVisible = val;
        if (val) {
          this.getList();
        }
      },
      immediate: true
    }
  },
  methods: {
    /** 查询审批流程模板列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error("获取模板列表失败:", error);
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 关闭对话框
    handleClose() {
      this.selectedTemplate = null;
      this.$emit('update:visible', false);
      this.$emit('close');
    },
    // 创建新模板
    createNewTemplate() {
      // 关闭当前对话框并打开模板创建页面
      this.$emit('update:visible', false);
      this.$router.push('/supply/template');
    },
    // 行点击事件
    handleRowClick(row) {
      this.selectedTemplate = row;
    },
    // 选择模板
    selectTemplate(row) {
      this.selectedTemplate = row;
      console.log('已在选择器中选中模板:', row.id, row.templateName);
    },
    // 确认选择
    confirmSelection() {
      if (this.selectedTemplate) {
        // 确保将完整模板对象传递，包含id属性
        console.log('将选择的模板传递给父组件:', this.selectedTemplate);
        this.$emit('select', this.selectedTemplate);
        this.handleClose();
      } else {
        this.$message.warning('请选择一个审批流程模板');
      }
    },
    /** 预览按钮操作 */
    handlePreview(row) {
      if (!row.processNodes) {
        this.$modal.msgError("该模板没有流程设计内容，无法预览");
        return;
      }

      try {
        const formData = JSON.parse(row.processNodes);
        // 确保节点有nodeId
        if (formData.nodes && formData.nodes.length) {
          formData.nodes.forEach(node => {
            if (!node.nodeId) {
              node.nodeId = this.generateNodeId();
            }
          });
        }

        this.previewData = formData;
        this.previewData.orderId = row.orderId;
        this.previewOpen = true;
      } catch (e) {
        this.$modal.msgError("流程设计数据解析错误，无法预览");
        console.error("预览流程数据解析错误", e);
      }
    },
    /** 生成节点唯一ID */
    generateNodeId() {
      return 'node_' + new Date().getTime() + '_' + Math.floor(Math.random() * 1000);
    },
    // 审批流程类型翻译
    flowTypeFormat(row, column) {
      const flowTypes = {
        'purchase': '采购审批',
        'sales': '销售审批',
        'hr': '人事审批',
        'finance': '财务审批',
        'other': '其他审批'
      };
      return flowTypes[row.flowType] || row.flowType;
    },
    // 格式化多个审批角色
    formatRoles(roleKeys) {
      if (!roleKeys || !roleKeys.length) return '无';
      return roleKeys.join(', ');
    },
    // 格式化审批人员
    formatApprovalUsers(userIds) {
      if (!userIds || !userIds.length) return '无';
      return userIds.join(', ');
    },
    // 获取签名图片
    getSignatureImages(signatureImage) {
      if (!signatureImage) return [];
      // 分割逗号分隔的图片链接
      return signatureImage.split(',').filter(img => img.trim() !== '');
    }
  }
};
</script>

<style lang="scss" scoped>
.selector-container {
  min-height: 400px;
}

.mb8 {
  margin-bottom: 8px;
}

.flow-preview-container {
  width: 100%;
  height: 500px;
  overflow: auto;
  border: 1px solid #ebeef5;
  background-color: #fafafa;
  padding: 20px;
}

.flow-preview {
  .no-data {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #909399;

    i {
      font-size: 32px;
      margin-bottom: 10px;
    }
  }

  .flow-start, .flow-end {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;

    .start-node, .end-node {
      width: 100px;
      height: 40px;
      border-radius: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;

      i {
        margin-right: 5px;
      }
    }

    .start-node {
      background-color: #e1f3d8;
      color: #67c23a;
      border: 1px solid #67c23a;
    }

    .end-node {
      background-color: #fef0f0;
      color: #f56c6c;
      border: 1px solid #f56c6c;
    }

    .flow-connector {
      height: 30px;
      width: 2px;
      background-color: #dcdfe6;
      margin: 5px 0;
    }
  }

  .flow-node-wrapper {
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;

    .flow-node {
      width: 300px;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      background-color: #f8f8f8;

      .node-icon {
        display: inline-block;
        margin-right: 8px;
        color: #409EFF;
      }

      .node-content {
        .node-title {
          font-weight: bold;
          margin-bottom: 10px;
          padding-bottom: 5px;
          border-bottom: 1px solid #ebeef5;
        }

        .node-info {
          font-size: 13px;
          color: #606266;

          p {
            margin: 5px 0;
          }
        }
      }
    }

    .flow-connector {
      height: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;

      &:before {
        content: '';
        position: absolute;
        top: 0;
        bottom: 0;
        left: 50%;
        width: 2px;
        background-color: #dcdfe6;
        transform: translateX(-50%);
      }

      i {
        position: relative;
        z-index: 1;
        background-color: #fff;
        color: #dcdfe6;
      }
    }
  }
}

.signature-images {
  margin-top: 10px;

  p {
    margin-bottom: 8px;
    font-weight: bold;
    color: #606266;
  }

  .image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .signature-thumb {
      width: 60px;
      height: 60px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 2px;
      cursor: pointer;

      &:hover {
        border-color: #409EFF;
      }
    }

    .image-error {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      background: #f5f7fa;
      color: #909399;
      font-size: 14px;
    }
  }
}

.signature-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;

  .signature-thumb {
    width: 40px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 2px;
    cursor: pointer;

    &:hover {
      border-color: #409EFF;
    }
  }

  .image-error {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 14px;
  }
}

.success-icon {
  color: #67c23a;
}
</style>
